<template>
    <div class="main">
        <div class="login-box">
            <h1 class="color-primary">{{ pageTitle }}</h1>
            <div class="content" v-if="!resetPwdVisible">
                <el-tabs>
                    <el-tab-pane label="账号登录">
                        <el-form class="form" :model="formData" :rules="rules" ref="formRef">
                            <el-form-item prop="username">
                                <el-input placeholder="请输入用户名或手机号" v-model="formData.username" name="username" prefix-icon="User" />
                            </el-form-item>
                            <el-form-item prop="password">
                                <password-input v-model="formData.password" @enter="doLogin" />
                            </el-form-item>
                            <div class="buttons">
                                <el-button type="primary" class="button" @click="doLogin" :loading="loading">登录</el-button>
                                <div class="text-right lh-3" v-if="messageEnabled">
                                    <el-link type="primary" @click="resetPassword">忘记密码</el-link>
                                </div>
                            </div>
                            <div class="color-red error-msg">
                                {{ errorInfo.msg }}
                            </div>

                            <div v-if="errorInfo.restCount <= 3" class="color-red">
                                <span v-if="errorInfo.restCount <= 0">用户已锁定，请10分钟后再试</span>
                                <span v-else>剩余尝试次数：{{ errorInfo.restCount }}，如超出尝试次数用户将锁定10分钟</span>
                            </div>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="手机号登录" v-if="messageEnabled">
                        <PhoneLogin @next="goNextPage" />
                    </el-tab-pane>
                </el-tabs>
            </div>
            <div class="content" v-else>
                <div class="sub-title">
                    <span class="title font-bold"> 密码重置 </span>
                </div>
                <resetPwd @close="resetPwdVisible = false" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { login } from "@/apis/login.js";
import * as sysApis from "@/apis/sys.js";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { setToken } from "../../../utils/token";
import passwordInput from "@/components/password-input.vue";
import { useSysStore } from "../../../store";
import resetPwd from "./reset-pwd.vue";
import PhoneLogin from "./phone-login.vue";

const router = useRouter();
const formData = ref({});
const rules = reactive({
    username: {
        required: true,
        message: "用户名或手机号不能为空",
    },
    password: {
        required: true,
        message: "密码不能为空",
    },
    code: {
        required: true,
        message: "验证码不能为空",
    },
});
const formRef = ref();
const errorInfo = ref({
    restCount: 10,
});
const sysStore = useSysStore();
const pageTitle = document.title;
const loading = ref(false);
const resetPwdVisible = ref(false);
const messageEnabled = computed(() => {
    let userConfig = sysStore.getUserConfig();
    return userConfig.messageEnabled;
});

app.utils.setTheme("default", "default");

onMounted(() => {
    // 如果用户登录过，那么跳转到对应页面或首页

    const userInfo = sysStore.getUserInfo();
    if (userInfo.userId) {
        // 登录过
        goNextPage();
        return;
    }

    // 退出登录
    app.https.get("/auth/logout");
});

// 跳转页面
function goNextPage() {
    // 如果链接中带有next，则跳转next，否则跳转首页
    const next = router.currentRoute.value.query?.next;
    if (!next || next.startsWith("/login")) {
        // 如果带有redirectUri
        let redirectUri = router.currentRoute.value.query?.redirectUri;
        if (redirectUri) {
            app.https.get("/sys/app/auth/code").then((resp) => {
                if (redirectUri.includes("?")) {
                    redirectUri += "&code=" + resp;
                } else {
                    redirectUri += "?code=" + resp;
                }

                window.open(redirectUri, "_self");
            });
            return;
        } else {
            router.replace("/");
        }
    } else {
        // window.open(next, "_self");
        router.replace(next);
    }
}

// 进行登录
function doLogin() {
    formRef.value.validate((resp) => {
        if (!resp) {
            return;
        }

        loading.value = true;

        app.https
            .get("/auth/logout")
            .then(() => {
                login(formData.value)
                    .then((resp) => {
                        setToken(resp.accessToken);

                        sysApis.getInitInfo().then((resp) => {
                            ElMessage.success("登录成功");
                            const sysStore = useSysStore();
                            sysStore.init(resp);
                            setTimeout(() => {
                                goNextPage();
                            }, 30);
                        });
                    })
                    .catch((err) => {
                        console.log(err);
                        errorInfo.value = err;
                    })
                    .finally(() => (loading.value = false));
            })
            .catch(() => (loading.value = false));
    });
}

function resetPassword() {
    resetPwdVisible.value = true;
}
</script>

<style lang="scss" scoped>
@media screen and (min-width: 600px) {
    .login-box {
        width: 500px;
        right: 20%;
    }
}

@media screen and (max-width: 600px) {
    .login-box {
        width: 100%;
        padding: 0 16px;
        box-sizing: border-box;
    }
}

.main {
    background-image: url("/bg.webp");
    background-size: cover;
    width: 100%;
    height: 100%;
}

.login-box {
    position: absolute;
    top: 20%;

    h1 {
        text-align: center;
        margin-bottom: 60px;
        color: #fff;
    }

    .content {
        box-shadow: 0 4px 16px 0 rgb(33 37 46 / 12%);
        padding: 48px;
        line-height: 58px;
        background-color: #fff;
        border-radius: 2px;

        .sub-title {
            font-size: 18px;
            text-align: left;
            margin-bottom: 32px;

            .title {
                padding: 0 8px 4px 8px;
                border-bottom: 4px solid var(--primary_color);
            }
        }

        .buttons {
            margin-top: 16px;

            .button {
                width: 100%;
                height: 40px;
            }
        }

        .form {
            :deep() {
                .el-input {
                    --el-input-height: 48px;
                }
            }
        }

        .bottom-buttons {
            line-height: 24px;
        }
    }

    .error-msg {
        line-height: 1;
    }
}
</style>
